//
//  Login.m
//  ChampoinPeso
//
//  Created by mac on 2025/2/19.
//

#import "Login.h"
#import "DataFrameWeb.h"
#import "LocationUpdata.h"
@interface Login ()<UITextFieldDelegate>
@property (nonatomic,strong)UITextField *phone;
@property (nonatomic,strong)UITextField *code;
@property (nonatomic,strong)UIButton *codebtn;
@property (nonatomic, strong)NSTimer *countdownTimer;
@property (nonatomic, assign) NSInteger countdownTime;
@property (nonatomic,strong)UIButton *agree;
@property (nonatomic,strong)UIButton *login;

@end

@implementation Login

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIImageView *bgIV = [[UIImageView alloc] initWithFrame:self.view.bounds];
    bgIV.image = [UIImage imageNamed:@"login_bg"];
    [self.view addSubview:bgIV];
    [self setupUI];
    
}


-(void)setupUI
{
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    [back setImage:[UIImage imageNamed:@"login_close"] forState:UIControlStateNormal];
    [self.view addSubview:back];
    [back mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-19);
        make.top.mas_offset(80);
        make.size.mas_equalTo(CGSizeMake(20, 20));
        ;    }];
    [[back rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self dismissViewControllerAnimated:NO completion:nil
        ];
    }];
    UIView *phoneView = [UIView new];
    phoneView.backgroundColor = HexColor(@"#F7F7F7");
    phoneView.layer.cornerRadius = 27;
    [self.view addSubview:phoneView];
    [phoneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(25);
        make.right.mas_offset(-25);
        make.top.mas_offset(KWidth(220)+ MarginTop + 20 + 64);
        make.height.mas_equalTo(54);
    }];
    
    UILabel *lab = [UILabel new];
    lab.text = @"+63";
    lab.textColor = HexColor(@"#000000");
    lab.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    [phoneView addSubview:lab];
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(17);
        make.centerY.mas_equalTo(phoneView);
    }];
    
    [phoneView addSubview:self.phone];
    [_phone mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(60);
        make.centerY.mas_equalTo(phoneView);
        make.right.mas_offset(0);
    }];
    
    UIView *codeView = [UIView new];
    codeView.backgroundColor = HexColor(@"#F7F7F7");
    codeView.layer.cornerRadius = 27;
    [self.view addSubview:codeView];
    [codeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(25);
        make.right.mas_offset(-25);
        make.top.equalTo(phoneView.mas_bottom).offset(12);
        make.height.mas_equalTo(54);
    }];
    
    [codeView addSubview:self.code];
    [_code mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(17);
        make.centerY.mas_equalTo(codeView);
        make.right.mas_offset(-100);
    }];
    UIButton *codebtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [codebtn setTitle:@"Get code" forState:UIControlStateNormal];
    [codebtn setTitleColor:HexColor(@"#2C64FF") forState:UIControlStateNormal];
    [codeView addSubview:codebtn];
    [codebtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-17);
        make.centerY.mas_equalTo(codeView);
    }];
    _codebtn = codebtn;
    [codebtn addTarget:self action:@selector(startCountdown) forControlEvents:UIControlEventTouchUpInside];

    UIButton *code = [UIButton buttonWithType:UIButtonTypeCustom];
    [code setImage:[UIImage imageNamed:@"login_lau_img"] forState:UIControlStateNormal];
    [self.view addSubview:code];
    [code mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(codeView.mas_bottom).offset(22);
        make.centerX.mas_equalTo(self.view);
    }];
    [code addTarget:self action:@selector(getLCode) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *agree = [UIButton buttonWithType:UIButtonTypeCustom];
    [agree setImage:[UIImage imageNamed:@"login_agree_no"] forState:UIControlStateNormal];
    [agree setImage:[UIImage imageNamed:@"login_agree"] forState:UIControlStateSelected];
    agree.selected = YES;
    [self.view addSubview:agree];
    [agree mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_offset(-bottomSafeHeight - 20 );
        make.left.mas_offset(30);
        make.size.mas_equalTo(CGSizeMake(20, 20));
    }];
    [agree addTarget:self action:@selector(agree:) forControlEvents:UIControlEventTouchUpInside];
    UILabel *agreeLab = [UILabel new];
    agreeLab.text = @"I’ve confirm and agree to the";
    agreeLab.textColor = DetailColor;
    agreeLab.font  = [UIFont systemFontOfSize:13];
    [self.view addSubview:agreeLab];
    [agreeLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(agree.mas_right).offset(5);
        make.centerY.mas_equalTo(agree);
    }];
    
    UIButton *gree = [UIButton buttonWithType:UIButtonTypeCustom];
    [gree setTitle:@"<Privacy agreement>" forState:UIControlStateNormal];
    gree.titleLabel.font  = [UIFont systemFontOfSize:13];
    [gree setTitleColor:HexColor(@"#2C64FF") forState:UIControlStateNormal];
    [self.view addSubview:gree];
    [gree mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(agreeLab.mas_right).offset(2);
        make.centerY.mas_equalTo(agree);
    }];
    _agree = agree;
    UIButton *login = [UIButton buttonWithType: UIButtonTypeCustom];
    [login setBackgroundColor:DetailColor];
    login.layer.cornerRadius = 27;
    [login setTitle:@"Login" forState:UIControlStateNormal];
    login.titleLabel.font = [UIFont systemFontOfSize:18 weight:UIFontWeightMedium];
    [login setTitleColor:MainColor forState:UIControlStateNormal];
    login.userInteractionEnabled = NO;
    [self.view addSubview:login];
    [login mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(25);
        make.right.mas_offset(-25);
        make.height.mas_equalTo(54);
        make.bottom.equalTo(agree.mas_top).offset(-50);
    }];
    _login = login;
    [[login rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [SCRequest postHUDWithUrl:@"/cham/gardening" params:@{@"ofamber":self.phone.text,@"yankees":self.code.text} isMsg:YES success:^(id  _Nonnull responseObject) {
            if ([responseObject[@"gardening"] isEqualToString:@"0"]) {
                
                [[NSUserDefaults standardUserDefaults] setObject:self.phone.text forKey:@"phone"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                [[NSUserDefaults standardUserDefaults] setObject:responseObject[@"fashion"][@"stewardess"] forKey:@"stewardess"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                [self startMark:@"1"];
                [self dismissViewControllerAnimated:YES completion:nil];
                [self showAutoMessage:responseObject[@"hobby"] ToView:self.view];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"loginscuess" object:self];
            }
        } failure:^(NSError * _Nonnull error) {
        }];
    }];
    [[gree rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self dismissViewControllerAnimated:NO completion:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"gotoAgree" object:self ];
    }];
}

//-(void)agree11:(UIButton*)sender
//{
//    [self dismissViewControllerAnimated:NO completion:nil];
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"gotoAgree" object:self ];
//}
//-(void)login:(UIButton*)btn{
//    [DataFrameMove frameMoverForPost:@"/cham/gardening" MoverPost:YES frameParm:@{@"ofamber":self.phone.text,@"yankees":self.code.text} finish:^(id  _Nonnull info) {
//        //stewardess
//        [[NSUserDefaults standardUserDefaults] setObject:self.phone.text forKey:@"phone"];
//        [[NSUserDefaults standardUserDefaults] synchronize];
//        [[NSUserDefaults standardUserDefaults] setObject:info[@"fashion"][@"stewardess"] forKey:@"stewardess"];
//        [[NSUserDefaults standardUserDefaults] synchronize];
//        [self startMark:@"1"];
//        [self dismissViewControllerAnimated:YES completion:nil];
//        [self showAutoMessage:info[@"hobby"] ToView:self.view];
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"loginscuess" object:self];
//
//    }];
//}
-(void)pCode{
    [SCRequest postHUDWithUrl:@"/cham/few" params:@{@"greyhair":self.phone.text} isMsg:YES success:^(id  _Nonnull responseObject) {
        if ([responseObject[@"gardening"] isEqualToString:@"0"]) {
            
            self.countdownTime = 60;
            self.codebtn.enabled = NO;
            self.countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats:YES];
            [self showAutoMessage:responseObject[@"hobby"] ToView:self.view];
            [self.code becomeFirstResponder];
            [[LocationUpdata sharedInstance] startMarkTag];
            [self showAutoMessage:responseObject[@"hobby"] ToView:self.view];
        }
    } failure:^(NSError * _Nonnull error) {
    }];

//    [DataFrameMove frameMoverForPost:@"/cham/few" MoverPost:YES frameParm:@{@"greyhair":self.phone.text} finish:^(id  _Nonnull info) {
//        self.countdownTime = 60;
//        self.codebtn.enabled = NO;
//        self.countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats:YES];
//        [self showAutoMessage:info[@"hobby"] ToView:self.view];
//        [self.code becomeFirstResponder];
//        [[LocationUpdata sharedInstance] startMarkTag];
//        [self showAutoMessage:info[@"hobby"] ToView:self.view];
//    }];
}

-(void)agree:(UIButton*)sender{
    sender.selected = !sender.selected;
    if ([_phone.text length]  > 0 && [_code.text length]  > 0 && _agree.selected) {
        _login.userInteractionEnabled = YES;
        [_login setBackgroundColor:HexColor(@"#9DDD04")];
    }else{
        _login.userInteractionEnabled = NO;
        [_login setBackgroundColor:DetailColor];
    }

}
-(UITextField *)phone
{
    if (!_phone) {
        _phone = [UITextField new];
        _phone.font = [UIFont systemFontOfSize:14];
        _phone.placeholder  = @"Enter cell number";
        _phone.textColor = UIColor.blackColor;
        _phone.borderStyle = UITextBorderStyleNone;
        _phone.delegate = self;
        _phone.keyboardType = UIKeyboardTypeNumberPad;
        _phone.returnKeyType = UIReturnKeySearch;
        NSAttributedString *attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Enter cell number" attributes:@{NSForegroundColorAttributeName: HexColor(@"#CBC9C9")}];
        _phone.attributedPlaceholder = attributedPlaceholder;
        [_phone addTarget:self
                           action:@selector(textFieldDidChange:)
                 forControlEvents:UIControlEventEditingChanged];

    }
    return _phone;
}

-(UITextField *)code
{
    if (!_code) {
        _code = [UITextField new];
        _code.font = [UIFont systemFontOfSize:14];
        _code.placeholder  = @"Enter cell number";
        _code.textColor = UIColor.blackColor;
        _code.borderStyle = UITextBorderStyleNone;
        _code.delegate = self;
        _code.keyboardType = UIKeyboardTypeNumberPad;
        _code.returnKeyType = UIReturnKeySearch;
        NSAttributedString *attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Enter cell number" attributes:@{NSForegroundColorAttributeName: HexColor(@"#CBC9C9")}];
        _code.attributedPlaceholder = attributedPlaceholder;
        [_code addTarget:self
                           action:@selector(textFieldDidChange:)
                 forControlEvents:UIControlEventEditingChanged];
    }
    return _code;
}


-(void)getLCode{
    if ([CPS(self.phone.text) isEqualToString:@""]) {
        return;
    }
    [SCRequest postHUDWithUrl:@"/cham/orchestra" params:@{@"greyhair":self.phone.text} isMsg:YES success:^(id  _Nonnull responseObject) {
        if ([responseObject[@"gardening"] isEqualToString:@"0"]) {
            
            [self showAutoMessage:responseObject[@"hobby"] ToView:self.view];
            [self.code becomeFirstResponder];
            [[LocationUpdata sharedInstance] startMarkTag];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
//    [DataFrameMove frameMoverForPost:@"/cham/orchestra" MoverPost:YES frameParm:@{@"greyhair":self.phone.text} finish:^(id  _Nonnull info) {
//        [self showAutoMessage:info[@"hobby"] ToView:self.view];
//        [self.code becomeFirstResponder];
//        [[LocationUpdata sharedInstance] startMarkTag];
//        [self showAutoMessage:info[@"hobby"] ToView:self.view];
//    }];
}
- (void)startCountdown {
    if ([CPS(self.phone.text) isEqualToString:@""]) {
        return;
    }
    [self pCode];
    if (self.countdownTimer) {
        return;
    }
}

- (void)updateCountdown {
    NSString *title = [NSString stringWithFormat:@"%lds", (long)self.countdownTime];
    [self.codebtn setTitleColor:HexColor(@"#8D8D8D") forState:UIControlStateNormal];
    [self.codebtn setTitle:title forState:UIControlStateDisabled];
    self.countdownTime--;
    if (self.countdownTime < 0) {
        [self.countdownTimer invalidate];
        self.countdownTime = 60;
        self.countdownTimer = nil;
        self.codebtn.enabled = YES;
        [self.codebtn setTitle:@"Re-obtain" forState:UIControlStateNormal];
        [self.codebtn setTitleColor:HexColor(@"#FFB633") forState:UIControlStateNormal];
    }
}
-(void)textFieldDidChange:(UITextField *)sender{
    if ([_phone.text length]  > 0 && [_code.text length]  >0 && _agree.selected) {
        _login.userInteractionEnabled = YES;
        [_login setBackgroundColor:HexColor(@"#2C64FF")];
    }else{
        _login.userInteractionEnabled = NO;
        [_login setBackgroundColor:DetailColor];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
